import React from 'react';
import {
  Card,
  Result,
  Button,
  Space,
  Typography
} from 'antd';
import {
  ReloadOutlined,
  HomeOutlined,
  BugOutlined
} from '@ant-design/icons';

const { Text, Title } = Typography;

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasError: false,
      error: null
    };
  }

  static getDerivedStateFromError(error) {
    return {
      hasError: true,
      error
    };
  }

  componentDidCatch(error, errorInfo) {
    console.error('应用发生错误:', error, errorInfo);
  }

  // 重试功能
  handleRetry = () => {
    this.setState({
      hasError: false,
      error: null
    });
  };

  // 回到首页
  handleGoHome = () => {
    window.location.href = '/dashboard';
  };

  render() {
    if (this.state.hasError) {
      const { error } = this.state;

      return (
        <>
          {/* 黑客风格动画背景样式 */}
          <style>
            {`
              @keyframes gradientShift {
                0% { background-position: 0% 50%; }
                50% { background-position: 100% 50%; }
                100% { background-position: 0% 50%; }
              }
              
              @keyframes float {
                0%, 100% { transform: translateY(0px) rotate(0deg); }
                33% { transform: translateY(-10px) rotate(2deg); }
                66% { transform: translateY(5px) rotate(-1deg); }
              }
              
              @keyframes slideIn {
                from { 
                  opacity: 0; 
                  transform: translateY(30px) scale(0.95); 
                }
                to { 
                  opacity: 1; 
                  transform: translateY(0px) scale(1); 
                }
              }
              
              @keyframes matrixRain {
                0% { transform: translateY(-100vh) rotate(0deg); opacity: 1; }
                100% { transform: translateY(100vh) rotate(360deg); opacity: 0; }
              }
              
              @keyframes codeScroll {
                0% { transform: translateX(100vw); }
                100% { transform: translateX(-100vw); }
              }
              
              @keyframes binaryPulse {
                0%, 100% { opacity: 0.3; color: #00ff88; }
                50% { opacity: 1; color: #0080ff; }
              }
              
              @keyframes hexFlicker {
                0%, 100% { opacity: 0.6; }
                25% { opacity: 1; }
                75% { opacity: 0.8; }
              }
              
              @keyframes glitch {
                0%, 100% { transform: translate(0); }
                20% { transform: translate(-2px, 2px); }
                40% { transform: translate(-2px, -2px); }
                60% { transform: translate(2px, 2px); }
                80% { transform: translate(2px, -2px); }
              }
              
              .error-bg {
                background: 
                  radial-gradient(circle at 25% 25%, #0a0a23 0%, transparent 50%),
                  radial-gradient(circle at 75% 75%, #1a1a2e 0%, transparent 50%),
                  linear-gradient(-45deg, #0f3460, #16213e, #0e4749, #533b5c);
                background-size: 100% 100%, 100% 100%, 400% 400%;
                animation: gradientShift 12s ease infinite;
              }
              
              .error-card {
                animation: slideIn 0.8s ease-out;
              }
              
              .floating-icon {
                animation: float 3s ease-in-out infinite;
              }
              
              .matrix-bg {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
                pointer-events: none;
                z-index: 1;
              }
              
              .matrix-char {
                position: absolute;
                font-family: 'Courier New', monospace;
                font-weight: bold;
                font-size: 18px;
                color: #00ff88;
                text-shadow: 0 0 10px #00ff88;
                animation: matrixRain linear infinite;
                opacity: 0.7;
              }
              
              .code-line {
                position: absolute;
                font-family: 'Courier New', monospace;
                font-size: 12px;
                color: rgba(0, 255, 136, 0.6);
                white-space: nowrap;
                animation: codeScroll linear infinite;
                text-shadow: 0 0 5px rgba(0, 255, 136, 0.5);
              }
              
              .binary-bg {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                overflow: hidden;
                pointer-events: none;
                z-index: 0;
              }
              
              .binary-text {
                position: absolute;
                font-family: 'Courier New', monospace;
                font-size: 14px;
                font-weight: bold;
                animation: binaryPulse 3s ease-in-out infinite;
                text-shadow: 0 0 8px currentColor;
              }
              
              .hex-particle {
                position: absolute;
                font-family: 'Courier New', monospace;
                font-size: 10px;
                color: #4a9eff;
                animation: hexFlicker 2s ease-in-out infinite;
                text-shadow: 0 0 6px #4a9eff;
              }
              
              .glitch-text {
                animation: glitch 0.3s ease-in-out infinite;
              }
              
              .cyber-grid {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-image: 
                  linear-gradient(rgba(0, 255, 136, 0.1) 1px, transparent 1px),
                  linear-gradient(90deg, rgba(0, 255, 136, 0.1) 1px, transparent 1px);
                background-size: 50px 50px;
                animation: gridMove 20s linear infinite;
                pointer-events: none;
                z-index: 0;
              }
              
              @keyframes gridMove {
                0% { transform: translate(0, 0); }
                100% { transform: translate(50px, 50px); }
              }
            `}
          </style>

          <div className="error-bg" style={{
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '20px',
            position: 'relative'
          }}>
            {/* 赛博朋克网格背景 */}
            <div className="cyber-grid"></div>

            {/* 二进制背景 */}
            <div className="binary-bg">
              {Array.from({ length: 30 }).map((_, i) => {
                const binaryString = Math.random().toString(2).substring(2, 12);
                return (
                  <div
                    key={`binary-${i}`}
                    className="binary-text"
                    style={{
                      top: `${Math.random() * 100}%`,
                      left: `${Math.random() * 100}%`,
                      animationDelay: `${Math.random() * 3}s`,
                      animationDuration: `${2 + Math.random() * 2}s`
                    }}
                  >
                    {binaryString}
                  </div>
                );
              })}
            </div>

            {/* Matrix字符雨效果 */}
            <div className="matrix-bg">
              {Array.from({ length: 15 }).map((_, i) => {
                const chars = ['0', '1', 'A', 'B', 'C', 'D', 'E', 'F', '2', '3', '4', '5', '6', '7', '8', '9'];
                const char = chars[Math.floor(Math.random() * chars.length)];
                return (
                  <div
                    key={`matrix-${i}`}
                    className="matrix-char"
                    style={{
                      left: `${Math.random() * 100}%`,
                      animationDuration: `${3 + Math.random() * 4}s`,
                      animationDelay: `${Math.random() * 5}s`,
                      fontSize: `${14 + Math.random() * 8}px`
                    }}
                  >
                    {char}
                  </div>
                );
              })}
            </div>

            {/* 代码滚动效果 */}
            {[
              'Error: Cannot read property of undefined',
              'TypeError: Failed to fetch resource',
              'ReferenceError: Component is not defined',
              'SyntaxError: Unexpected token',
              '404: Resource not found',
              'NetworkError: Connection timeout'
            ].map((code, i) => (
              <div
                key={`code-${i}`}
                className="code-line"
                style={{
                  top: `${10 + i * 15}%`,
                  animationDuration: `${8 + Math.random() * 4}s`,
                  animationDelay: `${Math.random() * 3}s`,
                  opacity: 0.4
                }}
              >
                {'> '}{code}{'...'}
              </div>
            ))}

            {/* 十六进制粒子 */}
            <div style={{ position: 'absolute', width: '100%', height: '100%', pointerEvents: 'none' }}>
              {Array.from({ length: 20 }).map((_, i) => {
                const hexValue = Math.floor(Math.random() * 16777215).toString(16).toUpperCase().padStart(6, '0');
                return (
                  <div
                    key={`hex-${i}`}
                    className="hex-particle"
                    style={{
                      top: `${Math.random() * 100}%`,
                      left: `${Math.random() * 100}%`,
                      animationDelay: `${Math.random() * 2}s`,
                      animationDuration: `${1.5 + Math.random()}s`
                    }}
                  >
                    0x{hexValue.substring(0, 4)}
                  </div>
                );
              })}
            </div>

            <Card
              className="error-card"
              style={{
                maxWidth: 520,
                width: '100%',
                borderRadius: 24,
                border: 'none',
                boxShadow: '0 25px 80px rgba(0,0,0,0.3), 0 0 0 1px rgba(255,255,255,0.1), 0 0 40px rgba(0, 255, 136, 0.1)',
                background: 'transparent',
                backdropFilter: 'blur(25px)',
                position: 'relative',
                overflow: 'hidden',
                zIndex: 10
              }}
              styles={{
                body: {
                  padding: '48px 40px',
                  textAlign: 'center',
                  position: 'relative'
                }
              }}
            >
              {/* 顶部装饰线 */}
              <div style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                height: 4,
                background: 'linear-gradient(90deg, #6366f1, #8b5cf6, #06b6d4, #10b981)',
                backgroundSize: '200% 100%',
                animation: 'gradientShift 3s ease infinite'
              }} />

              {/* 错误图标 */}
              <div style={{ marginBottom: 32 }}>
                <div className="floating-icon" style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: 80,
                  height: 80,
                  borderRadius: '50%',
                  background: 'linear-gradient(135deg, #fef3c7, #fcd34d)',
                  marginBottom: 16
                }}>
                  <BugOutlined style={{
                    fontSize: 32,
                    color: '#f59e0b'
                  }} />
                </div>
              </div>

              {/* 错误标题 */}
              <Title level={2} className="glitch-text" style={{
                color: '#1f2937',
                margin: '0 0 16px 0',
                fontSize: 32,
                fontWeight: 700,
                background: 'linear-gradient(135deg,rgb(230, 230, 230), #374151)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text',
                textShadow: '0 0 10px rgba(31, 41, 55, 0.3)'
              }}>
                System Error 💀
              </Title>

              {/* 错误描述 */}
              <Text style={{
                color: '#6b7280',
                fontSize: 18,
                display: 'block',
                marginBottom: 24,
                lineHeight: 1.6,
                fontFamily: 'Inter, -apple-system, sans-serif'
              }}>
                <span style={{ color: '#ef4444', fontWeight: 600 }}>Fatal Error Detected</span>
                <br />
                系统遇到了意外的异常，正在启动修复协议...
              </Text>

              {/* 错误代码 */}
              {error?.message && (
                <div style={{
                  background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.8), rgba(30, 41, 59, 0.9))',
                  borderRadius: 12,
                  padding: '16px 20px',
                  marginBottom: 32,
                  border: '1px solid rgba(0, 255, 136, 0.2)',
                  boxShadow: '0 0 20px rgba(0, 255, 136, 0.1), inset 0 0 20px rgba(0, 255, 136, 0.05)'
                }}>
                  <div style={{
                    fontSize: 11,
                    color: '#00ff88',
                    marginBottom: 8,
                    fontFamily: '"JetBrains Mono", "Fira Code", Consolas, monospace',
                    opacity: 0.8
                  }}>
                    {'>'} SYSTEM_ERROR_LOG
                  </div>
                  <Text style={{
                    fontSize: 13,
                    color: '#ff6b6b',
                    fontFamily: '"JetBrains Mono", "Fira Code", Consolas, monospace',
                    wordBreak: 'break-word',
                    textShadow: '0 0 5px rgba(255, 107, 107, 0.3)'
                  }}>
                    {error.message}
                  </Text>
                  <div style={{
                    fontSize: 10,
                    color: '#4a9eff',
                    marginTop: 8,
                    fontFamily: '"JetBrains Mono", "Fira Code", Consolas, monospace',
                    opacity: 0.6
                  }}>
                    {'>'} ERROR_CODE: 0x{Math.floor(Math.random() * 0xFFFF).toString(16).toUpperCase().padStart(4, '0')}
                  </div>
                </div>
              )}

              {/* 操作按钮 */}
              <Space size={16}>
                <Button
                  type="primary"
                  icon={<ReloadOutlined />}
                  size="large"
                  onClick={this.handleRetry}
                  style={{
                    borderRadius: 16,
                    height: 48,
                    padding: '0 28px',
                    fontSize: 16,
                    fontWeight: 600,
                    background: 'linear-gradient(135deg, #00ff88, #0080ff)',
                    border: '2px solid rgba(0, 255, 136, 0.3)',
                    color: '#000',
                    boxShadow: '0 4px 20px rgba(0, 255, 136, 0.4), inset 0 0 20px rgba(0, 255, 136, 0.1)',
                    transition: 'all 0.3s ease',
                    textShadow: '0 1px 2px rgba(0, 0, 0, 0.2)'
                  }}
                  onMouseEnter={(e) => {
                    e.target.style.transform = 'translateY(-2px)';
                    e.target.style.boxShadow = '0 8px 30px rgba(0, 255, 136, 0.6), inset 0 0 30px rgba(0, 255, 136, 0.2)';
                    e.target.style.borderColor = 'rgba(0, 255, 136, 0.6)';
                  }}
                  onMouseLeave={(e) => {
                    e.target.style.transform = 'translateY(0px)';
                    e.target.style.boxShadow = '0 4px 20px rgba(0, 255, 136, 0.4), inset 0 0 20px rgba(0, 255, 136, 0.1)';
                    e.target.style.borderColor = 'rgba(0, 255, 136, 0.3)';
                  }}
                >
                  刷新页面
                </Button>
                <Button
                  icon={<HomeOutlined />}
                  size="large"
                  onClick={this.handleGoHome}
                  style={{
                    borderRadius: 16,
                    height: 48,
                    padding: '0 28px',
                    fontSize: 16,
                    fontWeight: 600,
                    background: 'linear-gradient(135deg, rgba(74, 158, 255, 0.1), rgba(139, 92, 246, 0.1))',
                    borderColor: '#4a9eff',
                    color: '#4a9eff',
                    border: '2px solid rgba(74, 158, 255, 0.3)',
                    boxShadow: '0 4px 20px rgba(74, 158, 255, 0.2)',
                    transition: 'all 0.3s ease',
                    textShadow: '0 0 5px rgba(74, 158, 255, 0.3)'
                  }}
                  onMouseEnter={(e) => {
                    e.target.style.transform = 'translateY(-2px)';
                    e.target.style.borderColor = '#4a9eff';
                    e.target.style.boxShadow = '0 8px 30px rgba(74, 158, 255, 0.4)';
                    e.target.style.background = 'linear-gradient(135deg, rgba(74, 158, 255, 0.2), rgba(139, 92, 246, 0.2))';
                  }}
                  onMouseLeave={(e) => {
                    e.target.style.transform = 'translateY(0px)';
                    e.target.style.borderColor = 'rgba(74, 158, 255, 0.3)';
                    e.target.style.boxShadow = '0 4px 20px rgba(74, 158, 255, 0.2)';
                    e.target.style.background = 'linear-gradient(135deg, rgba(74, 158, 255, 0.1), rgba(139, 92, 246, 0.1))';
                  }}
                >
                  返回主页
                </Button>
              </Space>
            </Card>
          </div>
        </>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
